﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;




namespace XYZshell.Game.CardGameEngine
{
	/// <summary>
	/// 牌堆类
	/// </summary>
	[Serializable]
	public class Deck : GameObject
	{
		protected  Queue<Card> cardsQueue = new Queue<Card>();
		Random r = new Random(DateTime.Now.Millisecond);
		/// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="cardSet">将要包含在该牌堆里的卡组</param>
		public Deck( CardCollection cardSet )
		{

			
			foreach (Card c in cardSet)
			{
				cardsQueue.Enqueue( c );
			}
			Shuffle();
		}
		public Deck()
		{

		}
		/// <summary>
		/// 牌堆使用的卡组,只读,对该集合的任何操作不会保存
		/// </summary>
		public CardCollection Cards
		{
			get
			{
				return new CardCollection( cardsQueue.ToList() );
			}
		
		}

		/// <summary>
		/// 洗牌
		/// </summary>
		public void Shuffle()
		{

			IList<Card> cards = cardsQueue.ToList();

			cardsQueue.Clear();
			

			while (cards.Count > 0)
			{
				int index = r.Next(cards.Count);
				cardsQueue.Enqueue(cards[index]);
				cards.RemoveAt(index);
			}
		}

		/// <summary>
		/// 抽牌
		/// </summary>
		/// <returns></returns>
		public Card Siphon()
		{
			Card card= cardsQueue.Dequeue();
			return card;
		}
		/// <summary>
		/// 根据名称选择指定的牌
		/// </summary>
		/// <param name="cardName"></param>
		/// <returns></returns>
		public Card Select(string cardName)
		{
			if (cardsQueue.Count != Cards.Count)
			{
				Shuffle();
			}


			
			//Queue<Card>.Enumerator ie = cardsQueue.GetEnumerator();
			//do
			//{
			//    if (ie.Current.Name == cardName)
			//        return ie.Current;
			//} while (ie.MoveNext());
			//return null;
			Card card=  cardsQueue.First<Card>(c => c.Name == cardName);
			//Cards.Remove( card );
			return card;
			
		}
		/// <summary>
		///  发牌
		/// </summary>
		/// <param name="player">目标玩家</param>
		public void Send( Player player )
		{
			Card card= cardsQueue.Dequeue();
			player.Hand.Add( card );
		}
	}
}
